//common.js
var config = require("./dev_config.js");
var md5 = require("./md5.js");
config = config.getConfig();
var systemInfo = {};
function reqService(url, params, systemInfo, method = 'POST', cb){
    params = createSign(params, systemInfo);
    wx.request({
      url: config.apiHost+url,
      method: method ? "GET" : "POST",
      data: params,
      success:function(res){
        if(config.debug){
            console.log('接口: '+url+"\n参数: "+JSON.stringify(params)+"\n返回值: "+JSON.stringify(res.data))
        }
        typeof cb == "function" && cb(res.data)
      }
    })
}

function toast(that, msg = ''){
    that.setData({status: false, msg:msg});
}

function createSign(params, systemInfo){
    var baseParams = createBaseParams(systemInfo);
    params = Object.assign(params, baseParams);
    var paramsKey = Object.keys(params).sort();
    
    params = sortParamsByKey(params)
    var params_str = "";
    for(var v in params){
        params_str += v+params[v];
    }

    var sign = md5.hex_md5(params_str);
    
    params['sign'] = sign;
    return params;
}

function sortParamsByKey(params){
    var newParams = {};
    var key_sort = Object.keys(params).sort();
    for(key in key_sort){
        var key = key_sort[key];
        newParams[key] = params[key]
    }

    return newParams;
}

function createBaseParams(systemInfo){
    var timestamp = Date.parse(new Date());
    var params = {
        "device_name": systemInfo.model,
        "v": config.appVersion,
        "os": config.appOS,
        "osv": systemInfo.version,
        "t": timestamp / 1000,
        "sk": GetRandomNum(111111,999999),
        "chn": config.appChn
    };

    return params;
}



function GetRandomNum(Min,Max)
{   
    var Range = Max - Min;   
    var Rand = Math.random();   
    return (Min + Math.round(Rand * Range));   
}   

module.exports = {
  reqService: reqService,
  toast: toast
}